package org.example;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

// 标记此类为Spring配置类（替代XML配置文件）
@Configuration
public class ThreadPoolConfig {

    // 定义线程池Bean，交由Spring容器管理
    @Bean(name = "taskExecutor") // Bean的名称为taskExecutor
    public Executor threadPoolExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数：线程池长期维持的线程数量
        executor.setCorePoolSize(3);
        // 最大线程数：线程池可扩展的最大线程数量
        executor.setMaxPoolSize(5);
        // 队列容量：任务等待队列的长度
        executor.setQueueCapacity(10);
        // 线程名称前缀：便于日志排查
        executor.setThreadNamePrefix("MyThreadPool-");
        // 拒绝策略：当线程池和队列都满时，由提交任务的线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化线程池
        executor.initialize();
        return executor;
    }

    // 定义任务服务Bean，交由Spring容器管理
    @Bean
    public TaskService taskService() {
        return new TaskService();
    }
}
